package Entities;


import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Observable;
import java.util.Observer;
import Server.ConnectionToClient;
import Server.OriginatorMessage;
import Server.RsWraper;

/**
 * The Class ServerEntity implements Observer interface.
 * 
 */
public class ServerEntity implements Observer{
	private String host;
	private String port;

	/** The connection. */
	private Connection conn;
	
	/* (non-Javadoc)
	 * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
	 */
	@Override
	public void update(Observable arg0, Object arg1) {
		OriginatorMessage message = (OriginatorMessage) arg1;
		ConnectionToClient client = message.getOriginator();
		String str = (String) message.getMessage();
		
				try{
					if(str.equals("Connection closed"))
						client.close();
					else
					if(str.startsWith("#"))
						System.out.println(message.getMessage());
					else{
					PreparedStatement preparedStatement = conn.prepareStatement(str);
					if(str.startsWith("INSERT")||str.startsWith("UPDATE")||str.startsWith("DELETE")){
						preparedStatement.executeUpdate();
						client.sendToClient("#Server:Action succeded");
					}
					else{
						ResultSet rs = preparedStatement.executeQuery();
						RsWraper rw=new RsWraper(rs);
						if(rw.getRowCounter()==0)
							client.sendToClient("empty query");
						else
						client.sendToClient(rw);
							}
					}
				}
				catch(SQLException sql)
				{
					int sqlreadexception=0, sqlwriteexception=1062;
					if(sql.getErrorCode()==sqlreadexception || sql.getErrorCode()==sqlwriteexception)
						try {
							client.sendToClient("error");
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					else
						try {
							sql.printStackTrace();
							client.sendToClient("not read/write sql exception");
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						}	
				
	}
	
	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
	}

	/**
	 * Gets the connection.
	 *
	 * @return the connection
	 */
	public Connection getConn() {
		return conn;
	}
	
	/**
	 * Sets the connection.
	 *
	 * @param conn the new connection
	 */
	public void setConn(Connection conn) {
		this.conn = conn;
	}
	
	
}
